package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.AdChannelService;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.aliyun.GreeTextScan;
import com.heima.aliyun.GreenImageScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {


    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    GreeTextScan greeTextScan;

    @Autowired
    GreenImageScan greenImageScan;

    @Autowired
    AdSensitiveMapper adSensitiveMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 自媒体文章审核   根据当前id自动审核这篇文章
     *
     * @param wmNewsId
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        //1.当自媒体用户提交发布文章之后，会发消息给kafka提交审核，平台运营端接收文章信息
        //2.根据自媒体文章id查询文章信息
        if (wmNewsId == null) {
            log.error("autoScanByMediaNewsId wmNewsId is null");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //远程调用feign接口,如果这个文章没有查到也抛出异常
        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        if (wmNews == null) {
            log.error("autoScanByMediaNewsId wmNews is null");
            CustException.cust(AppHttpCodeEnum.NEWS_NOT_EXIT);
        }
        //3.如果当前文章的状态为4（人工审核通过），则无需再进行自动审核审核，保存app文章相关数据即可
        //4.文章状态为8,发布时间小于等于当前时间,则直接保存app文章相关数据
        if ((wmNews.getStatus() == 4 && wmNews.getSubmitedTime().getTime() <= System.currentTimeMillis()) ||
                (wmNews.getStatus() == 8 && wmNews.getSubmitedTime().getTime() <= System.currentTimeMillis())) {
            //如果是以上三种情况的话可以直接保存app数据
            ResponseResult result = saveArticle(wmNews);//根据wmNews保存三张表的关系
            wmNews.setArticleId((long)result.getData());
            updataWmNewsMsg(wmNews,(short)9,"文章已发布");
            return;
        }
        //前置:处理文章中的文本和url信息
        List<String> imageUrlList = null;
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            //如果封面信息不为空  把被封面信息转换为url的list集合
            String images = wmNews.getImages();
            String[] split = images.split(",");
            imageUrlList = new ArrayList<>();
            for (String s : split) {
                s = webSite + s;
                imageUrlList.add(s);
                //可以把封面的url的list集合和内容的url集合放在同一对象中方便图片审核
            }
        }
        List<Map> content = JSON.parseArray(wmNews.getContent(), Map.class);

        StringBuilder stringBuilder = new StringBuilder();
        //把文章内容中的文字部分连接成字符串,把文章中的图像部分搞成url的list集合
        for (Map<String, String> map : content) {
            if (map.get("type").equals("text")) {
                //如果是文本的就一直加
                String tpye = map.get("value");
                stringBuilder.append(tpye).append("_hmtt_");
                //拼接无意义字符串防止出现拼接性敏感词汇
            }
            if (map.get("type").equals("image")) {
                //如果是图片的url的话就把这个url拼接到list中去
                imageUrlList.add(map.get("value"));
            }
        }
        String title = wmNews.getTitle();
        stringBuilder.append(title);  //拼接标题
        //5.文章状态为1，则进行自动审核
        if (wmNews.getStatus() == 1) {
            //5.11  阿里云审核之后,本地敏感词汇也应该被审核   这里调用了dfa算法
            List<String> allSensitive = adSensitiveMapper.findAllSensitive();
            SensitiveWordUtil.initMap(allSensitive);
            Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(stringBuilder.toString());
            if (stringIntegerMap.size() > 0) {
                updataWmNewsMsg(wmNews, (short) 2, "文章中包含敏感词信息,不可发布");
                return;
            }

            //5.1   调用阿里云文本反垃圾服务，进行文本审核，如果审核不成功或需要人工审核，修改自媒体文章状态为2
            try {
                if(stringBuilder.toString().length()>10000){
                    CustException.cust(AppHttpCodeEnum.TO_LONG_CONTENT);
                }
                Map textMap = greeTextScan.greeTextScan(stringBuilder.toString());
                if (textMap.get("suggestion").equals("block")) {
                    //文章中包含敏感信息直接拒绝
                    updataWmNewsMsg(wmNews, (short) 2, "文章中包含敏感词信息,不可发布");
                    return;
                }
                if (textMap.get("suggestion").equals("review")) {
                    //文章中包含不确定信息转为人工审核
                    updataWmNewsMsg(wmNews, (short) 3, "文章或包含敏感信息需转入人工审核");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("文本解析失敗或者文本中包含了一些錯誤信息");
                updataWmNewsMsg(wmNews, (short) 3, "解析文章内容失败,需要人工审核");
                return;
            }

            //5.2 调用阿里云图片审核服务，如果审核不通过或需要人工审核，修改自媒体文章状态为2
            if (imageUrlList != null) {
                //图片去重
                imageUrlList = imageUrlList.stream().distinct().collect(Collectors.toList());
                try {
                    Map imageMap = greenImageScan.imageUrlScan(imageUrlList);
                    if (imageMap.get("suggestion").equals("block")) {
                        //文章中包含敏感信息直接拒绝
                        updataWmNewsMsg(wmNews, (short) 2, "图片内容违规,不可发布");
                        return;
                    }
                    if (imageMap.get("suggestion").equals("review")) {
                        //文章中包含不确定信息转为人工审核
                        updataWmNewsMsg(wmNews, (short) 3, "图片或包含敏感信息需转入人工审核");
                        return;
                    }
                    System.out.println(imageMap);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("需要人工審核,或者圖片中包含了一些敏感信息");
                        updataWmNewsMsg(wmNews, (short) 3, "解析图片失败,需要人工审核");
                    return;
                }
            }
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                //5.4 自媒体文章发布时间大于当前时间，修改自媒体文章状态为8（审核通过待发布状态）
                wmNews.setStatus((short) 8);
                wemediaFeign.updateWmNews(wmNews);
                return;
            }


        }
        //6.保存app相关数据
        ResponseResult result = saveArticle(wmNews);//根据wmNews保存三张表的关系
        wmNews.setArticleId((long)result.getData());
        //5.5 审核通过，修改自媒体文章状态为 9 （审核通过）同时回填app文章id到自媒体表中
        updataWmNewsMsg(wmNews,(short)9,"文章已发布");
        //7.创建索引（为后续app端的搜索功能做数据准备）
    }

    private void updataWmNewsMsg(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.DATA_UPDATA_FAIL);
        }
    }

    @Autowired
    AdChannelService adChannelService;

    @Autowired
    ArticleFeign articleFeign;

    private ResponseResult saveArticle(WmNews wmNews) {

        System.out.println("saveArticle方法调用成功............");
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        dto.setId(null);
        if (wmNews.getArticleId() != null) {
            //如果没有文章id的话就把
            dto.setId(wmNews.getArticleId());
        }
//      查询频道  频道设置
        AdChannel adChannel = adChannelService.getById(wmNews.getChannelId());
        if (StringUtils.isNotBlank(adChannel.getName())) {
            dto.setChannelName(adChannel.getName());
        }
        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());
        //保存文章  成功的话返回true 失败的话抛出异常
        dto.setContent(wmNews.getContent());

        //作者的相关信息保存
        WmUser user = wemediaFeign.findWmUserById(wmNews.getUserId());
        if (user == null || user.getStatus() != 9) {
            CustException.cust(AppHttpCodeEnum.AUTHOR_MSG_DONT_EXIT);
        }
//        dto.setAuthorId(user.getAp);
        dto.setAuthorName(user.getName());
        //远程调用feign  保存三张表信息
        return articleFeign.saveArticle(dto);

    }
}